﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SSAT.Commands;

namespace SSAT.Utils.Freezer
{
    /// <summary>
    /// This class allows you to enable/disable
    /// a group of controls in one shot.
    /// </summary>
    internal sealed class ControlFreezer
    {
        private List<FreezedItem> _freezedControls;
        private bool _isFreezed;

        public bool IsFreezed
        {
            get { return _isFreezed; }
        }

        public event EventHandler OnUnfreezed;

        public void AddControl(Control control)
        {
            AddControl(new FreezedControl(control));
        }

        public void AddControl(ToolStripItem control)
        {
            AddControl(new FreezedToolStripItem(control));
        }

        public void AddControl(CommandBase command)
        {
            AddControl(new FreezedCommand(command));
        }

        public void AddControl(FreezedItem control)
        {
            Verification.CheckArgumentForNull(control, "control");
            CheckWhetherFreezedControlsListIsNull();
            _freezedControls.Add(control);
        }

        private void CheckWhetherFreezedControlsListIsNull()
        {
            if (_freezedControls == null)
            {
                _freezedControls = new List<FreezedItem>();
            }
        }

        public void AddAListOfControls(IList<Control> controls)
        {
            Verification.CheckArgumentForNull(controls, "controls");
            foreach (Control ctrl in controls)
            {
                AddControl(ctrl);
            }
        }

        /// <summary>
        /// Disables controls.
        /// </summary>
        public void Freeze()
        {
            foreach (FreezedItem ctrl in _freezedControls)
            {
                try
                {
                    ctrl.Disable();
                }
                catch (Exception ex)
                {
                    Logging.Handle(ex);
                }
            }
            _isFreezed = true;
        }

        /// <summary>
        /// Enables controls.
        /// </summary>
        public void Unfreeze()
        {
            foreach (FreezedItem ctrl in _freezedControls)
            {
                try
                {
                    ctrl.Enable();
                }
                catch (Exception ex)
                {
                    Logging.Handle(ex);
                }
            }
            _isFreezed = false;
            if (OnUnfreezed != null)
            {
                OnUnfreezed(this, EventArgs.Empty);
            }
        }

        public void Clear()
        {
            _freezedControls.Clear();
            _freezedControls = null;
        }
    }
}
